import React from 'react';
import ReactDOM from 'react-dom';
import {List, Toast} from 'antd-mobile';
import mirror, {actions, connect} from 'mirrorx';
import {getCertiTypeEnglish, getGenderEnglish, getRelationEnglish, getSA, getCoveragePeriod, getPaymentPeriod, getPayMode, getBenefitPeriod} from './staticData';
import { createForm } from 'rc-form';
import RowInput from '../../component/Item/Input';
import RowSelect from '../../component/Item/Select';
import RowDate from '../../component/Item/DatePicker';
import Factor from '../../component/factor';
import Job from './job';
import RiskNotice from './riskNotice';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            applicantInfo: {
                applicantCertType: 'SHENFENZHENG',
            },  // 投保人信息
            insurantInfo: {
                insurantCertType: 'SHENFENZHENG'
            },   // 被保人信息
            factorInfo: {
                socialInsurance: "YES"
            },     // 保费试算因子信息
        };
    }

    componentDidMount() {
        let Insure = JSON.parse(sessionStorage.getItem('Insure'));
        let calculateVals = JSON.parse(sessionStorage.getItem('calculateVals'));
        if(calculateVals){
            this.onChangeFactor(calculateVals)
        }
        if(Insure){
            this.setState({applicantInfo: Insure})
        }
    }

    onChangeApplicant = (obj) => {
        if(obj.hasOwnProperty('applicantCertNo')){
            var a = this.isIdCard(Object.values(obj)[0])
            if( Object.prototype.toString.call(a) == "[object Object]" ){
                Object.assign(this.state.applicantInfo, {
                    applicantBirthday: new Date(a.birthday).getTime(),
                    applicantGender: a.genderCode
                })
                this.setState({applicantInfo: this.state.applicantInfo})
            }
        }
        Object.assign(this.state.applicantInfo, obj)
        this.setState({applicantInfo: this.state.applicantInfo})
    }

    onChangeInsurant = (obj) => {
        if(obj.relation == 'SELF'){
            const {applicantName, applicantCertType, applicantCertNo, applicantBirthday,
                applicantGender, applicantMobile, applicantEmail} = this.state.applicantInfo;
            Object.assign(this.state.insurantInfo, {
                insurantName: applicantName,
                insurantCertType: applicantCertType,
                insurantCertNo: applicantCertNo,
                insurantMobile: applicantMobile,
                insurantEmail: applicantEmail,
            })
            this.onChangeFactor({
                birthday: applicantBirthday,
                gender: applicantGender
            });
        }
        if(obj.hasOwnProperty('insurantCertNo')){
            var a = this.isIdCard(Object.values(obj)[0])
            if( Object.prototype.toString.call(a) == "[object Object]" ){
                Object.assign(this.state.factorInfo, {
                    birthday: new Date(a.birthday).getTime(),
                    gender: a.genderCode
                })
                this.onChangeFactor(this.state.factorInfo);
            }
        }
        Object.assign(this.state.insurantInfo, obj)
        this.setState({insurantInfo: this.state.insurantInfo})
    }

    onChangeFactor = (obj) => {
        Object.assign(this.state.factorInfo, obj)
        this.setState({factorInfo: this.state.factorInfo})
        let params = [{
            "bizTopic": "PREMIUM",
            "factorParams": this.state.factorInfo,
            "id": T.urlQuery('planId') // 计划id
        }]; 
        T.fetch({ //保费试算
            url:'/cal/premium/amount.json',
            data:params
        }).then((res)=>{
            if(res.success){
                this.setState({amount: res.value[0].calResp.calValue})
            }
        })
    }

    onChangeRiskNotice = (obj) => {
        this.setState(obj)
    }

    isIdCard = (card) => {
        if (!card) return true;
        var num = card.toUpperCase();
        //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
        if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
            return false;
        }
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        //下面分别分析出生日期和校验位
        var len, re;
        var birthday,genderCode;
        len = num.length;
        if (len == 15) {

            //获取出生日期
            birthday = '19' + card.substring(6, 8) + "-" + card.substring(8, 10) + "-" + card.substring(10, 12);
            //获取性别
            genderCode = parseInt(card.substr(14, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
            return false;
            } else {
            //将15位身份证转成18位
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;

            num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            num += arrCh[nTemp % 11];
            }
        } else if (len == 18) {

            //获取出生日期
            birthday = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
            //获取性别
            genderCode = parseInt(card.substr(16, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
            return false;
            } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[nTemp % 11];
            if (valnum != num.substr(17, 1)) {
                return false;
            }
            }
        }
        return {
            birthday: birthday,
            genderCode: genderCode
        }
    }

    submitAction = () => {
        let tipsResult = JSON.parse(sessionStorage.getItem("tipsResult"));
        sessionStorage.setItem("Insure",  JSON.stringify(this.state.applicantInfo));
        let param = {
            ...this.state.applicantInfo,
            ensurePersons: [{
                ...this.state.insurantInfo,
                ensurePlanId: T.urlQuery('planId'),
                insurantPremium: this.state.amount,
                // insurantPremium: this.state.factorInfo.SA
            }],
            goodsId: T.urlQuery('goodId'),
            campaignId: T.urlQuery('campaignId'),
            tipsResult,
        };
        param.applicantMobile = param.applicantMobile && param.applicantMobile.replace(/ /g, "");
        param.ensurePersons[0].insurantMobile = param.ensurePersons[0].insurantMobile && param.ensurePersons[0].insurantMobile.replace(/ /g, "");
        param.ensurePersons[0].insurantBirthday = this.state.factorInfo.birthday;
        param.ensurePersons[0].insurantGender = this.state.factorInfo.gender;
        console.log('param', param)
        if( T.urlQuery('goodId') == '10' ){
            param.ensurePersons[0].insurance = this.state.factorInfo.socialInsurance;
        }
        if(!this.state.showRiskNotice){
            T.showError("Plear Agree Notice Of Insurance And Clauses Of Insurance");
        }else{
            this.requestSubmit(param)
        }

    }

    requestSubmit = (param) => {
        T.fetch({ 
            url:'/order/submit.json',
            loading:true,
            data:param
        }).then((res)=>{
            if(res.success){
                console.log("res", res)
                actions.routing.push({
                    pathname: 'pay-English',
                    search: `?id=${res.value.orderNo}`
                })
            }
        })
    }

    render() {
        let {applicantInfo, insurantInfo, factorInfo, goodId} = this.state;
        console.log(this.state)
        return (
            <div className="insure">
                <div className="title">Policyholder Info</div>
                <div>
                    <List>
                        <RowInput label="Name" name="applicantName" language='English' value={applicantInfo.applicantName} callback={this.onChangeApplicant} />
                        <RowSelect label="ID Type" name="applicantCertType" value={applicantInfo.applicantCertType} data={getCertiTypeEnglish()} callback={this.onChangeApplicant} />
                        <RowInput label="ID Number" name="applicantCertNo" language='English' value={applicantInfo.applicantCertNo} callback={this.onChangeApplicant} />
                        <RowDate label="Birthdate" name="applicantBirthday" language='English' value={applicantInfo.applicantBirthday} callback={this.onChangeApplicant} />
                        <RowSelect label="Gender" name="applicantGender" language='English' value={applicantInfo.applicantGender} data={getGenderEnglish()} callback={this.onChangeApplicant} />                 
                        <RowInput label="Phone Number" type="phone" name="applicantMobile" language='English' value={applicantInfo.applicantMobile} callback={this.onChangeApplicant} />
                        <RowInput label="E-mail" name="applicantEmail" language='English' value={applicantInfo.applicantEmail} callback={this.onChangeApplicant} />
                    </List>
                </div>
                <div className="title">Life Assured Info</div>
                <div>
                    <List>
                        <RowSelect label="For Whom" name="relation" language='English' value={insurantInfo.relation} data={getRelationEnglish()} callback={this.onChangeInsurant} />
                        <RowInput label="Name" name="insurantName" language='English' value={insurantInfo.insurantName} callback={this.onChangeInsurant} />
                        <RowSelect label="ID Type" name="insurantCertType" language='English' value={insurantInfo.insurantCertType} data={getCertiTypeEnglish()} callback={this.onChangeInsurant} />
                        <RowInput label="ID Number" name="insurantCertNo" language='English' value={insurantInfo.insurantCertNo} callback={this.onChangeInsurant} />
                        <RowDate label="Birthdate" name="birthday" language='English' value={factorInfo.birthday} callback={this.onChangeFactor} />
                        <RowSelect label="Gender" name="gender" language='English' value={factorInfo.gender} data={getGenderEnglish()} callback={this.onChangeFactor} />                        
                        <RowInput label="Phone Number" type="phone" name="insurantMobile" language='English' value={insurantInfo.insurantMobile} callback={this.onChangeInsurant} />
                        <RowInput label="E-mail" name="insurantEmail" language='English' value={insurantInfo.insurantEmail} callback={this.onChangeInsurant} />
                    </List>
                </div>
                <Factor callback={this.onChangeFactor} {...this.state.factorInfo} type={T.urlQuery('goodId')} />
                <RiskNotice callback={this.onChangeRiskNotice} language='English' goodId={T.urlQuery('goodId')} />
                <div className="footer">
                    <div className="footer-left">
                        <a className="f38 fc6 tac color-price">&nbsp;&nbsp;<span className="f30"></span><span id="totalMoney">${this.state.amount || 0}</span></a>
                    </div>
                    <div className="footer-right">
                        <a href="javascript:;"  className="f32 fcw diy_background" id="applyBtn" onClick={this.submitAction}>Confirm</a>
                    </div>
                </div>
            </div>
        )
    }
}

export default App;